package com.xdwanj.smartcity.data.repository.impl;

import android.util.Log;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.xdwanj.smartcity.App;
import com.xdwanj.smartcity.data.bean.result.Result;
import com.xdwanj.smartcity.data.repository.IUploadRepository;
import com.xdwanj.smartcity.data.request.UploadRequest;
import com.xdwanj.smartcity.util.EncodedUtils;

import java.util.Map;

public class UploadRepository implements IUploadRepository {
    private static final String TAG = "UploadRepository";
    private static UploadRepository INSTANCE = null;

    private UploadRepository() {
    }

    public static UploadRepository getInstance() {
        if (INSTANCE != null)
            return INSTANCE;
        else
            throw new IllegalStateException("not init");
    }

    public static void init() {
        INSTANCE = new UploadRepository();
    }


    @Override
    public LiveData<Boolean> upload(UploadRequest.FileEntity fileEntity, Map<String, Object> params) throws Exception {
        MutableLiveData<Boolean> data = new MutableLiveData<>();
        UploadRequest request = new UploadRequest("/prod-api/common/upload", params, fileEntity,
                response -> {
                    String str = EncodedUtils.remoteToLocal(response);
                    Result result = App.gson.fromJson(str, Result.class);
                    if (result.getCode().equals(200)) {
                        data.setValue(true);
                    } else {
                        data.setValue(false);
                    }
                },
                error -> {
                    Log.d(TAG, "upload: " + error);
                }
        );

        App.queue.add(
                request.setShouldCache(false)
                        .setTag(TAG)
        );
        return data;
    }
}
